package com.thx.addressbook.dao;

import com.thx.addressbook.model.Addressbook;
import com.thx.addressbook.model.AddressbookGroup;
import com.thx.common.orm.PaginationDao;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class AddressbookDao extends PaginationDao<Addressbook> {

  private static final Logger logger = LoggerFactory.getLogger(AddressbookDao.class);


  /**
   * 根据用户名称、所属租户id、所属分组id查询通讯录分页数据.
   * 
   * @param name 用户名称，可以为空
   * @param enterpriseId 企业所属租户id，不能为空
   * @param agId 所属分组id，可以为空
   * @return 企业所属租户id为空，返回空记录集
   */
  public List<Addressbook> findByNameAndAgIdAndEnterId(String name, Long enterpriseId, Long agId) {
    List<Addressbook> result = null;
    String hql = "from Addressbook ";
    List<Object> objs = new ArrayList<Object>();
    if (enterpriseId != null && enterpriseId != 0) {
      hql += " where enterpriseId = ? ";
      objs.add(enterpriseId);
      if (StringUtils.isNotBlank(name)) {
        hql += " and addressbookName like ? ";
        objs.add("%" + name + "%");
      }
      if (agId != null && agId != 0) {
        hql += " and agId =? ";
        objs.add(agId);
      }
      result = this.findPageList(hql, objs.toArray());
    }
    return result;
  }

  /**
   * 根据分组ID查询通信录人员 建立日期 : Apr 18, 2013 <br>.
   * 作者 : 王阿敏<br>
   * 
   * @param info
   * @return
   */
  public List<Addressbook> queryByAgId(Long agId) {
    String hql = "from Addressbook where agId = ? ";
    return createQuery(hql, agId).list();
  }

  /**
   * 根据姓名查询通信录人员 建立日期 : Apr 18, 2013 <br>.
   * 作者 : 王阿敏<br>
   * 
   * @param info
   * @return
   */
  public List<Addressbook> queryByName(String addressbookName, Long agId) {
    String hql = "from Addressbook where 1=1";
    if (addressbookName != null && !addressbookName.equals("")) {
      hql += " and addressbookName like '%" + addressbookName + "%'";
    }
    List<Addressbook> list = createQuery(hql).list();
    if (list.size() > 0) {
      return list;
    }
    return null;
  }

  /**
   * 查询通信录人员sql语句 建立日期 : Apr 18, 2013 <br>.
   * 作者 : 王阿敏<br>
   * 
   * @param info
   * @return
   */
  public String getHql(Addressbook info) {
    String hql = "from Addressbook c where 1=1";
    if (info.getAgId() != null && info.getAgId() != 0L) {
      hql += " and c.agId = " + info.getAgId();
    }
    if (StringUtils.isNotBlank(info.getAddressbookName())) {
      hql += " and c.addressbookName like '%" + info.getAddressbookName() + "%'";
    }
    if (info.getCreateId() != null) {
      hql += " and c.createId = " + info.getCreateId();
    }
    if (info.getEnterpriseId() != null) {
      hql += " and c.enterpriseId = " + info.getEnterpriseId();
    }
    return hql;
  }

  /**
   * 查询单个人员信息 建立日期 : Apr 18, 2013 <br>.
   * 作者 : 王阿敏<br>
   * 
   * @param entity
   * @return
   */
  public Addressbook queryPresonalOne(Addressbook entity) {
    String hql = "from Addressbook c where c.priId = ? and c.enterpriseId = ?";
    List<Addressbook> list =
        createQuery(hql, new Object[] {entity.getPriId(), entity.getEnterpriseId()}).list();
    if (list != null && list.size() > 0) {
      return list.get(0);
    }
    return null;
  }

  /**
   * 根据人员名称查询人员信息 建立日期 : Apr 18, 2013 <br>.
   * 作者 : 王阿敏<br>
   * 
   * @param entity
   * @return
   */
  public Addressbook getCategoryName(Addressbook entity) {
    String hql = "from Addressbook c where c.addressbookName = ? and c.enterpriseId = ?";
    List<Addressbook> list =
        createQuery(hql, new Object[] {entity.getAddressbookName(), entity.getEnterpriseId()})
            .list();
    if (list != null && list.size() > 0) {
      return list.get(0);
    }
    return null;
  }

  public void deletepersonalById(Long deptId) {
    this.delete(deptId);

  }

  /**
   * 查询个人通信录邮箱信息 建立日期 : June 14, 2013 <br>.
   * 作者 : 贺晋恩<br>
   * 
   * @param entity
   * @return
   */
  public Addressbook queryBymailandenpid(String mailname, Long enterpriseId,
      List<AddressbookGroup> grouplist) {
    if (grouplist != null && grouplist.size() > 0) {
      for (int i = 0; i < grouplist.size(); i++) {
        Long agid = grouplist.get(i).getAgId();
        String hql =
            "from Addressbook c where c.addressbookMail = ? and c.enterpriseId = ? and c.agId = ?";
        String mn = mailname.trim();
        List<Addressbook> list = createQuery(hql, new Object[] {mn, enterpriseId, agid}).list();
        if (list != null && list.size() > 0) {
          return list.get(0);
        }
      }
    }
    return null;
  }

  /**
   * 根据人员id、人员所属个人通讯录分类、姓名或邮箱按字符模糊查询通讯录列表.
   * 
   * @param queryChar 模糊查询字符
   * @param personalId 所属人员id,不能为空
   * @param acId 人员所属个人通讯录分类，不能为空
   * @return 所属人员id、个人通讯录分类为空，返回空记录集
   */
  public List<Addressbook> getByChar(String queryChar, String personalId, String acId) {
    List<Addressbook> result = null;
    String hql = "from Addressbook tt ";
    List<Object> objs = new ArrayList<Object>();
    if (StringUtils.isNotBlank(personalId) && StringUtils.isNotBlank(acId)) {
      hql +=" where tt.agId in (select t.agId  from AddressbookGroup t where t.personnelId =? and t.acId =?) ";
      objs.add(NumberUtils.toLong(personalId));
      objs.add(NumberUtils.toLong(acId));
      if (StringUtils.isNotBlank(queryChar)) {
        hql += " (tt.addressbookName like ? or tt.addressbookMail like ?) ";
        objs.add(queryChar + "%");
        objs.add(queryChar + "%");
      }
      result = this.createQuery(hql, objs.toArray()).list();
    }
    return result;
  }


  // /**
  // * 查询通信录人员列表页
  // * 建立日期 : Apr 18, 2013 <br>
  // * 作者 : 王阿敏<br>
  // * @param info
  // * @param start
  // * @param limit
  // * @return
  // */
  // public List<Addressbook> queryAllByCondition(Addressbook info, final int
  // start, final int limit) {
  // String hql = getHql((Addressbook)info);
  // List<Addressbook> list =
  // createQuery(hql).setFirstResult(start).setMaxResults(limit).list();
  // if(list.size()>0){
  // return list;
  // }else{
  // return null;
  // }
  // }
  // /**
  // * 查询通信录人员列表页数
  // * 建立日期 : Apr 18, 2013 <br>
  // * 作者 : 王阿敏<br>
  // * @param info
  // * @return
  // */
  // @SuppressWarnings("unchecked")
  // public int queryCount(Addressbook info) {
  // String hql = "select count(*) " +getHql((Addressbook)info);
  // List list = createQuery(hql).list();
  // if (list.size() > 0) {
  // Long count = (Long) list.get(0);
  // return new Integer(count + "");
  // }
  // return 0;
  // }
  // /**
  // * 根据人员ID查询人员信息
  // * 建立日期 : Apr 18, 2013 <br>
  // * 作者 : 王阿敏<br>
  // * @param priId
  // * @return
  // */
  // public Addressbook findById(Long priId){
  // String hql = "from Addressbook where priId = "+priId;
  // Addressbook addressbook = new Addressbook();
  // List<Addressbook> list =createQuery(hql).list();
  // if(list.size()>0){
  // addressbook = list.get(0);
  // }
  // return addressbook;
  // }

  // /**
  // * 查询通讯录数
  // *
  // * @author zhangyong
  // * @date 2013-12-16 下午04:15:58
  // * @param id
  // * @param startTime
  // * @param endTime
  // * @return
  // */
  // public int queryAddressbookNum(String id, CommonLogView commonLogView) {
  // StringBuilder sql = new StringBuilder();
  // Object[] o = new Object[] { id };
  // sql.append(" select count(*) tongji from addressbook tt ");
  // sql.append(
  // " where tt.enterprise_id in (select e.enterprise_id from enterprise e
  // where e.enterprise_id >? and e.enterprise_number not like '%test%')");
  // String startTime = commonLogView.getStartDate();
  // String endTime = commonLogView.getEndDate();
  // if (StringUtils.isNotBlank(commonLogView.getCityStr())) {
  // String[] cityStrings = commonLogView.getCityStr().split(",");
  // String cityString = "";
  // for (String city : cityStrings) {
  // if (cityString.equals("")) {
  // cityString = "'" + city.trim() + "'";
  // } else {
  // cityString += ",'" + city.trim() + "'";
  // }
  // }
  // sql.append(" and tt.enterprise_id in ( select e.enterprise_id from
  // enterprise e where e.BIZ_CITY in("
  // + cityString + ") ) ");
  // }
  // if (StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)) {
  // sql.append(" and to_char(tt.create_time,'yyyy-MM-dd hh24:mm:ss') >= ?");
  // o = new Object[] { id, startTime };
  // } else if (StringUtils.isNotBlank(endTime) &&
  // StringUtils.isBlank(startTime)) {
  // sql.append(" and to_char(tt.create_time,'yyyy-MM-dd hh24:mm:ss') <= ?");
  // o = new Object[] { id, endTime };
  // } else if (StringUtils.isNotBlank(startTime) &&
  // StringUtils.isNotBlank(endTime)) {
  // sql.append(" and to_char(tt.create_time,'yyyy-MM-dd hh24:mm:ss') >= ?");
  // sql.append(" and to_char(tt.create_time,'yyyy-MM-dd hh24:mm:ss') <= ?");
  // o = new Object[] { id, startTime, endTime };
  // }
  // Object obj = createSQLQuery(sql.toString(), o).uniqueResult();
  // if (obj != null) {
  // return Integer.parseInt(obj.toString());
  // } else {
  // return 0;
  // }
  // }

  /**
   * @author 贺晋恩.
   * @date 2014-2-13 上午11:01:35
   * @param enterpriseId
   * @param startdate2
   * @param enddate2
   * @return
   */
  public int queryByEntId(Long enterpriseId, String startdate2, String enddate2) {
    String hql = "select count(*) from Addressbook where enterpriseId =" + enterpriseId;
    if (StringUtils.isNotBlank(startdate2)) {
      hql += " and to_char(createTime,'yyyy-MM-dd') >='" + startdate2 + "'";
    }
    if (StringUtils.isNotBlank(enddate2)) {
      hql += " and to_char(createTime,'yyyy-MM-dd') <='" + enddate2 + "'";
    }
    Object obj = createQuery(hql).uniqueResult();
    if (obj != null) {
      return Integer.parseInt(obj.toString());
    } else {
      return 0;
    }
  }

  /**
   * wangxufeng add 20150313 客户端调用，查询通讯录下的人员.
   * 
   * @param info
   * @param start
   * @param limit
   * @return
   */
  @SuppressWarnings("unchecked")
  public List<Addressbook> queryAllByApp(Addressbook info) {
    String hql = getHql((Addressbook) info);
    List<Addressbook> list = createQuery(hql).list();
    return list;
  }

  // /**
  // * 获取个人通讯录最后一次的更新时间
  // *
  // * @author 冯晋首
  // * @date 2015-6-5 下午3:17:06
  // * @param enterpriseId
  // * @return
  // */
  // public String getPerAddressBookLastUpdateTime(Long enterpriseId, Long personnelId, String
  // agIds) {
  // String sql = "select to_char(max(m.maxdate),'yyyy-mm-dd hh24:mi:ss') from("
  // + "select max(t.create_time) maxdate from ADDRESSBOOK t where t.enterprise_id=? and
  // t.create_id=? and t.ag_id in ("
  // + agIds + ") union all "
  // + "select max(p.update_time) maxdate from ADDRESSBOOK p where p.enterprise_id=? and
  // p.create_id=? and p.ag_id in ("
  // + agIds + ")) m";
  // return (String) createSQLQuery(sql, enterpriseId, personnelId, enterpriseId,
  // personnelId).uniqueResult();
  // }
}
